package com.ecoolex.ying.space.api.graphql;


import com.alibaba.fastjson.JSONArray;
import com.ecoolex.framework.modularize.api.auth.user.ConsumerMemberAuthority;
import com.ecoolex.framework.modularize.api.service.storage.FileSize;
import com.ecoolex.framework.modularize.api.service.storage.MimeType;
import com.ecoolex.framework.modularize.api.service.storage.StorageInfo;
import com.ecoolex.framework.modularize.api.service.storage.StorageService;
import com.ecoolex.framework.modularize.api.service.storage.Upload;
import com.ecoolex.framework.modularize.api.service.storage.UploadLimit;
import com.ecoolex.framework.modularize.api.service.storage.UploadSource;
import com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module;
import com.ecoolex.framework.web.api.graphql2.annotation.MutationField;
import com.ecoolex.framework.web.api.graphql2.annotation.Source;
import com.ecoolex.framework.web.api.graphql2.annotation.TypeField;
import com.ecoolex.ying.space.entity.Feedback;
import com.ecoolex.ying.space.pojo.AddFeedbackDTO;
import com.ecoolex.ying.space.ws.FeedbackService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;

import java.util.List;
import java.util.stream.Collectors;

@GraphQL2Module(type = GraphQL2Module.Type.User, description = "反馈")
public class FeedbackGraphql {

    @Reference
    private FeedbackService feedbackService;

    @Autowired
    private StorageService storageService;

    @TypeField(type = Feedback.class, field = "images", description = "反馈图片")
    public List<StorageInfo> images(@Source Feedback source) {
        JSONArray array = JSONArray.parseArray(source.getImages());
        List<String> storageIdLsit = array.toJavaList(String.class);
        return storageIdLsit.stream().map(storageId -> storageService.get(storageId)).collect(Collectors.toList());
    }

    @MutationField(field = "uploadFeedbackImage", description = "上传反馈图片" )
    public StorageInfo uploadFeedbackImage(@NonNull Upload request) {
    	UploadSource uploadSource = new UploadSource("Feedback","Images");
        UploadLimit uploadLimit = new UploadLimit();
        uploadLimit.setMaxSize(FileSize.MB.byteLength(2));
        uploadLimit.setAllowMimeType(MimeType.IMAGE.commons());

        return storageService.upload(request,uploadSource,uploadLimit);
    }

    @MutationField(field = "addFeedback", description = "添加反馈")
    public Feedback addFeedback(@NonNull AddFeedbackDTO add, ConsumerMemberAuthority user) {
        String createUser = "";
        if (user.isLogin()) {
            add.setUserId(user.userId());
            createUser = user.userName();
        } 
        return feedbackService.addFeedback(add, createUser);
    }


}
